package com.ocom.human.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.entity.master.EntityCompanykeyInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.human.dao.IDaoCompanyKeyInfo;
import com.ocom.human.service.CompanyKeyInfoService;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.redis.aspect.CacheRedisAspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CompanyKeyInfoServiceImpl extends ServiceImpl<IDaoCompanyKeyInfo, EntityCompanykeyInfo> implements CompanyKeyInfoService {


    @Autowired
    IDaoCompanyKeyInfo companyKeyInfo;

    public static final String KEY_ALGORITHM = "RSA";

    private static final String PUBLIC_KEY = "PublicKey";

    private static final String PRIVATE_KEY = "PrivateKey";
    /**
     * 用于封装随机产生的公钥与私钥
     */
    private static Map<String, String> keyMap = new HashMap<>();
    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private final static int KEY_SIZE = 2048;



    /**
     * 随机生成密钥对
     */
    private static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        // 初始化密钥对生成器
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());

        System.out.println("公钥长度>>>"+publicKeyString.length());

        // 得到私钥字符串
        String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());

        System.out.println("私钥长度>>>"+privateKeyString.length());
        // 将公钥和私钥保存到Map
        //PUBLIC_KEY 表示公钥
        keyMap.put(PUBLIC_KEY, publicKeyString);
        //PRIVATE_KEY 表示私钥
        keyMap.put(PRIVATE_KEY, privateKeyString);
    }

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    private static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    private static String decrypt(String str, String privateKey) throws Exception {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(str);
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    @CacheRedisAspect(prefix="getComKeyInfo",element={"comId"})
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB)
    @Override
    public List<EntityCompanykeyInfo> getComKeyInfo(Long comId) {
        QueryWrapper<EntityCompanykeyInfo> query = Wrappers.query();
        query.eq("com_id",comId);
        query.orderByDesc("id").last("limit 2");
        return companyKeyInfo.selectList(query);
    }
}
